import axios from 'axios'
import { Message } from 'element-ui'
import Cookie from 'js-cookie' // 操作cookie
import router from '@/router'
// 1 2 3

// 1. 创建实例
const http = axios.create({
  // baseURL: 'http://localhost:7001', // 需要后端跨域
  timeout: 5000, // 过期时间
})
// 2. 拦截请求
http.interceptors.request.use(
  (config) => {
    const csrfToken = Cookie.get('csrfToken')
    // console.log('csrfToken:', csrfToken)
    // csrf token
    config.headers['x-csrf-token'] = csrfToken
    // console.log('本地存储:', JSON.parse(localStorage.getItem('state')))
    // console.log('------:', localStorage.getItem('token'))
    config.headers.token = localStorage.getItem('token') || ''
    // 5. 处理loding
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)
// 3. 拦截响应
http.interceptors.response.use(
  (response) => {
    console.log('response:', response)
    const res = response.data
    console.log('res:', res)
    if (res.code == 409) {
      console.log('-----------409')
      console.log(router, 'router-----------')
      router.push('/login')
      return
    }
    return response
  },
  (err) => {
    // 6. 处理错误状态
    Message.error(err)
    return Promise.reject(err)
  }
)

export default http
